package cn.itcast.aspect;

import cn.itcast.mapper.OperateLogMapper;
import cn.itcast.pojo.Common;
import cn.itcast.pojo.OperateLog;
import com.alibaba.fastjson2.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;

//@Aspect
//@Component
public class OperateLogAspect {
    //注入日志mapper
    //@Autowired
    private OperateLogMapper operateLogMapper;
    @Pointcut("execution( * cn.itcast.service.*.add*(..)) || execution(* cn.itcast.service.*.delete*(..))|| execution(* cn.itcast.service.*.update*(..))")
    public void pt(){}


    @Around("pt()")
    public Object empOperateLog(ProceedingJoinPoint pjp) throws Throwable {
        Object proceed = null;
        long start = System.currentTimeMillis();
        try {
            proceed = pjp.proceed();
            //返回执行结果
            return proceed;
        }finally {
            //记录日志
            OperateLog operateLog = new OperateLog();
            //设置操作时间
            operateLog.setOperateTime(LocalDateTime.now());
            //设置操作类名
            operateLog.setClassName(pjp.getSignature().getDeclaringTypeName());
            //设置操作方法名
            operateLog.setMethodName(pjp.getSignature().getName());
            //设置参数
            operateLog.setMethodParams(pjp.getArgs() == null ? "" : JSONObject.toJSONString(pjp.getArgs()));
            //设置返回值
            operateLog.setReturnValue(proceed == null ? "" : JSONObject.toJSONString(proceed));
            long end = System.currentTimeMillis();
            //设置耗时
            operateLog.setCostTime(end - start);
            //获取操作员工id
            int empId = Integer.parseInt(Common.get().toString());
            //设置操作员工id
            operateLog.setOperateEmpId(empId);
            //添加日志
            operateLogMapper.addLog(operateLog);
        }
    }
}
